package com.kaizen.messagehandler.auth;

import com.kaizen.codec.Invocation;
import com.kaizen.dispatcher.MessageHandler;
import com.kaizen.message.auth.AuthRequest;
import com.kaizen.message.auth.AuthResponse;
import com.kaizen.server.NettyChannelManager;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class AuthRequestHandler implements MessageHandler<AuthRequest> {


    @Autowired
    private NettyChannelManager nettyChannelManager;


    @Override
    public void execute(Channel channel, AuthRequest message) {
        // <1> 如果未传递 accessToken
        if (StringUtils.isEmpty(message.getAccessToken())) {
            AuthResponse authResponse = new AuthResponse().setCode(1).setMessage("认证 accessToken 未传入");
            channel.writeAndFlush(new Invocation(AuthResponse.TYPE, authResponse));
            return;
        }
        // <3> 将用户和 Channel 绑定
        // TODO 先直接使用 accessToken 作为 User
        nettyChannelManager.addUser(channel, message.getAccessToken());
        AuthResponse authResponse = new AuthResponse().setCode(0);
        channel.writeAndFlush(new Invocation(AuthResponse.TYPE, authResponse));
    }

    @Override
    public String getType() {
        return AuthRequest.TYPE;
    }
}
